package com.axialproject.health.exchange.demo;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.http.AuthSubUtil;
import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class AddUserServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(AddUserServlet.class.getName());

    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String appUrl = this.getServletContext().getInitParameter("AppUrl");

        if (!"google".equals(req.getParameter("connect"))) {
            resp.setContentType("text/plain");
            resp.getWriter().println("Sorry ... Only Google Health is supported right now.");
            return;
        }

        Patient patient = null; // this is the patient we plan to connect
        Patient gpatient = null; // this is the google account for the patient
        boolean sendLoginLink = false;
        EntityManager em = EMF.get().createEntityManager();
        try {
            patient = PatientManager.getPatientByUsernameAppName(em, req.getParameter("username"), "ringful-demo");
            if (patient == null) {
                patient = new Patient ();
                patient.setUsername(req.getParameter("username"));
                patient.setAppName("ringful-demo");
                PatientManager.savePatient(em, patient);

                sendLoginLink = true;

            } else {
                List <Patient> patients = PatientManager.getLinkedPatients (em, patient.getId());
                for (Patient p : patients) {
                    if ("google".equals(p.getAppName()) && p.getToken() != null) {
                        boolean validToken = false;
                        try {
                            Map<String, String> tokenInfo = AuthSubUtil.getTokenInfo(p.getToken(), null);
                            if (tokenInfo != null) {
                                validToken = true;
                            }
                        } catch (Exception te) {
                            log.log(Level.SEVERE, te.getMessage(), te);
                        }

                        if (validToken) {
                            gpatient = p;
                        }
                    }
                }

                if (gpatient == null) {
                    sendLoginLink = true;
                }
            }

        } catch (Exception e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            resp.setContentType("text/plain");
            resp.getWriter().println("There is a problem. Check the error log");
            return;
        } finally {
            em.close ();
        }

        if (sendLoginLink) {
            // Show the link
            UserService userService = UserServiceFactory.getUserService();
            String nextUrl = appUrl + "/google/after_login?patientId=" + patient.getId() + "&sig=1234";

            resp.setContentType("text/html");
            resp.getWriter().println("Step 2: Your user " + patient.getUsername () + " now need to follow <a href=\"" + userService.createLoginURL(nextUrl) + "\">this link</a> and log into his own Google account to finish the connection process");

        } else {
            // Already registered
            log.info("The username is already connected to Google");
            resp.setContentType("text/html");
            resp.getWriter().println("The username is already connected to Google id: " + gpatient.getEmail() + " <a href=\"/demo/index.jsp\">Go to demo front page</a>");
        }

    }
}
